//
//  DJHomeViewController.m
//  DualJoy
//
//  Created by lijunge on 2019/11/14.
//  Copyright © 2019 lijunge. All rights reserved.
//

#import "DJHomeViewController.h"
#import "DJSettingViewController.h"
#import "DJTool.h"
#import "DJConstant.h"
#import "DJConnectView.h"
#import <Masonry.h>
#import "PlayIn.h"
#import "AxcDrawPath.h"
#import "DJHomeNotiseView.h"
#import "DJLoginViewController.h"
#import <FBSDKLoginKit/FBSDKLoginKit.h>
#import "ProgressHUD.h"
@interface DJHomeViewController ()<PlayInDelegate,ConnectViewDelegate>

@property (nonatomic, strong) PlayIn *playIn;
@property (nonatomic, strong) DJConnectView *connectView;
@property (nonatomic, strong) DJHomeNotiseView *notiseView;
@property (nonatomic, strong) UIView *naviBarView;
@property (nonatomic, strong) UIButton *headImageButton;
@property (nonatomic, strong) UIButton *closeButton;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, assign) BOOL connecting;

@end

@implementation DJHomeViewController

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.view.backgroundColor = kVCBackColor;
    [self configSubViews];
    [self readUserInfoFromLocal];
    [self addNotificationObserver];
    self.connecting = NO;
}

- (void)configSubViews {
    
    UIImageView *backImageView = [[UIImageView alloc] init];
    backImageView.image = [UIImage imageNamed:@"launchImage"];
    [self.view addSubview:backImageView];
    
    UIView *naviBarView = [[UIView alloc] init];
    naviBarView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:naviBarView];
    
    [naviBarView addSubview:self.titleLabel];
    [naviBarView addSubview:self.headImageButton];

    self.connectView = [[DJConnectView alloc] init];
    self.connectView.delegate = self;
    [self.view addSubview:self.connectView];
    
    self.notiseView = [[DJHomeNotiseView alloc] init];
    self.notiseView.hidden = YES;
    //[self.view addSubview:self.notiseView];
    
    UILabel *versionlabel = [[UILabel alloc] init];
    versionlabel.backgroundColor = [UIColor clearColor];
    versionlabel.textAlignment = NSTextAlignmentCenter;
    versionlabel.text = @"Version 1.0.0";
    versionlabel.textColor = KScienceTechnologyBlue;
    versionlabel.font = [UIFont boldSystemFontOfSize:11];
    [self.view addSubview:versionlabel];
    
    CGFloat naviHeight = kDJNavBarHeight;
    CGFloat bottomMargin = kDJBottomMargin + 20;
   
    [backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [naviBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.height.mas_equalTo(naviHeight);
    }];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(naviBarView);
        make.height.mas_equalTo(44);
        make.bottom.equalTo(naviBarView.mas_bottom);
    }];
    
    [self.headImageButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(naviBarView.mas_right).offset(-20);
        make.width.height.mas_equalTo(44);
        make.top.equalTo(naviBarView).offset(kDJStatusBarHeight);
    }];

    [self.connectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(200);
        make.height.mas_equalTo(320);
        make.top.equalTo(naviBarView.mas_bottom).offset(60);
        make.centerX.equalTo(self.view);
    }];
    
    [versionlabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view.mas_bottom).offset(-bottomMargin);
        make.height.mas_equalTo(40);
    }];

}

- (void)readUserInfoFromLocal {
    
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults] valueForKey:@"user_info"];
    if ([DJTool validObj:dic]) {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            NSString *url = [dic valueForKey:@"user_image"];
            if ([DJTool validStr:url]) {
                NSError *error;
                NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url] options:NSDataReadingMappedIfSafe error:&error];
                UIImage *iconImage = [UIImage imageWithData:data];
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.headImageButton.layer.cornerRadius = 22.0;
                    self.headImageButton.clipsToBounds = YES;
                    [self.headImageButton setImage:iconImage forState:UIControlStateNormal];
                });
            }
        });
    } else {
        [self getUserInfoErrorLoginAgain];
    }
}

- (void)addNotificationObserver {
    
    if (![self.userType isEqualToString:@"2"]) {return;}
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(facebookProfileChangeNoti:) name:FBSDKProfileDidChangeNotification object:nil];
}

- (void)facebookProfileChangeNoti:(NSNotification *)noti {
    
    FBSDKProfile *profile = [FBSDKProfile currentProfile];
    NSURL *url = [profile imageURLForPictureMode:FBSDKProfilePictureModeNormal size:CGSizeMake(50, 50)];
    NSMutableDictionary *dic = [NSMutableDictionary new];
    [dic setValue:profile.userID forKey:@"user_id"];
    [dic setValue:profile.name forKey:@"user_name"];
    [dic setValue:url.absoluteString forKey:@"user_image"];
    [dic setValue:@"2" forKey:@"user_type"];
    [[NSUserDefaults standardUserDefaults] setValue:dic forKey:@"user_info"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self readUserInfoFromLocal];
}

- (void)showErrorAlertViewWithTitle:(NSString *)title {
    
    [ProgressHUD showError:title];
}

#pragma mark - Action

- (void)rightBarButtonTapped:(UIButton *)sender {
    
    DJSettingViewController *settingVC = [[DJSettingViewController alloc] init];
    [self.navigationController pushViewController:settingVC animated:YES];
//    [self presentViewController:settingVC animated:YES completion:nil];
}

#pragma mark - Private

- (void)destroyPlayIn {
    
    [self.playIn.playInView removeFromSuperview];
    self.playIn.playInView = nil;
}

#pragma mark - DJConnectView delegate

- (void)dj_connectViewStartConnect {
    
    if (self.connecting) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"正在连接呦，在等等呗。。。" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"残忍停止" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"断开连接");
            [self.connectView stopConnect];
            [self.playIn stopPlay];
            return;
        }];
        UIAlertAction *cancelConfirm = [UIAlertAction actionWithTitle:@"再等等" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alert addAction:actionConfirm];
        [alert addAction:cancelConfirm];
        [self presentViewController:alert animated:YES completion:nil];
    }
    self.connecting = YES;
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults] valueForKey:@"user_info"];
    if (![DJTool validObj:dic]) {
        [self getUserInfoErrorLoginAgain];
        return;
    }
    if (![DJTool validStr:self.userID]) {
        if ([dic.allKeys containsObject:@"user_id"]) {
            NSString *userID = [dic valueForKey:@"user_id"];
            if (![DJTool validStr:userID]) {
                [self getUserInfoErrorLoginAgain];
                return;
            }
            self.userID = userID;
        }
    }
    
    if (![DJTool validStr:self.userType]) {
        if ([dic.allKeys containsObject:@"user_type"]) {
            NSString *userType = [dic valueForKey:@"user_type"];
            if (![DJTool validStr:userType]) {
                [self getUserInfoErrorLoginAgain];
                return;
            }
            self.userType = userType;
        }
    }
    self.playIn = [PlayIn sharedInstance];
    self.playIn.delegate = self;
    [self.playIn startPlayWithUserId:self.userID userType:self.userType];
}

- (void)getUserInfoErrorLoginAgain {
    
    [self showErrorAlertViewWithTitle:@"请重新登录"];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"DualJoyLogin"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    DJLoginViewController *loginVC = [[DJLoginViewController alloc] init];
    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:loginVC];
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    keyWindow.rootViewController = navi;
}

- (void)dj_connectViewNotiseTapped {
    
    
}

- (void)closeAction {
 
    [self.playIn stopPlay];
    [self destroyPlayIn];
}

#pragma mark - PlayIn Delegate

- (void)onPlayInStart:(int)duration {
    
    [self.connectView connectDidSuccess];
    self.connecting = NO;
    [self.view addSubview:self.playIn.playInView];
    CGFloat closeBtnWH = 120;
    self.closeButton.frame = CGRectMake(self.view.frame.size.width - closeBtnWH - 10, kDJStatusBarHeight, closeBtnWH, 20);
    [self.playIn.playInView addSubview:self.closeButton];
}

- (void)onPlayInStop {
    
    self.connecting = NO;
    [self destroyPlayIn];
    [self.connectView connectDidSuccess];
}

- (void)onPlayInError:(NSDictionary *)error {
    
    NSLog(@"[ViewController] playin error: %@", error);
    self.connecting = NO;
    [self destroyPlayIn];
    [self.connectView connectDidFailed];
    
    NSString *infoString = [error valueForKey:@"info"];
    if ([DJTool validStr:infoString]) {
        [self showErrorAlertViewWithTitle:infoString];
    }
}


#pragma mark -

- (UIButton *)headImageButton {
    
    if (_headImageButton == nil) {
        UIButton *headImgButton = [[UIButton alloc] init];
        headImgButton.backgroundColor = [UIColor lightGrayColor];
        headImgButton.layer.cornerRadius = 22.0;
        [headImgButton addTarget:self action:@selector(rightBarButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
        _headImageButton = headImgButton;
    }
    return _headImageButton;
}

- (UILabel *)titleLabel {
    
    if (_titleLabel == nil) {
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.text = @"KALEIDOSCOPE";
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.font = [UIFont boldSystemFontOfSize:24];
        titleLabel.textColor = [UIColor whiteColor];
        _titleLabel = titleLabel;
    }
    return _titleLabel;
}

- (UIButton *)closeButton {
    if (!_closeButton) {
        UIButton *button = [[UIButton alloc] init];
        button.userInteractionEnabled = YES;
        button.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.4];
        button.titleLabel.font = [UIFont boldSystemFontOfSize:14];
        button.titleLabel.textColor = [UIColor whiteColor];
        button.contentMode = UIViewContentModeScaleAspectFit;
        button.titleLabel.adjustsFontSizeToFitWidth = YES;
        [button setTitle:@"Exit Kaleido" forState:UIControlStateNormal];
        [button addTarget:self action:@selector(closeAction) forControlEvents:UIControlEventTouchUpInside];
        _closeButton = button;
    }
    return _closeButton;
}


@end
